var timeout = 60000;

/**
 * 生成签名
 * 
 * @param {Json} data
 * @param {时间戳} timeStamp
 */
function generateSignature(data, timeStamp) {
	var signArr = [];
	signArr.push('timeStamp=' + timeStamp);
	if (data && data != {}) {
		data = objKeySort(data);
		var ary = [];
		for (var key in data) {
			if (data.hasOwnProperty(key)) {
				if (data[key] === undefined || data[key] === '' ) continue;
				ary.push(key + '=' + data[key]);
			}
		}
		if (ary.length > 0) {
			signArr.push(ary.join('&'));
		}
	}

	signArr.push('secret=' + SECRET);
	var signStr = signArr.join('&');
	console.log('signStr: ' + signStr);
	return hex_md5(Base64.encode(signStr));
}

function getToken(success, fail) {
	var state = app.getState();
	var token = state.token;
	var tokenTime = state.tokenTime;
	var currentTime = new Date().getTime();
	if ((currentTime - tokenTime) >= 36000000) {
		var url = BASE_URL + 'cc/login/authorizationApp';
		var params = {
			"ApiKey": state.user.enginnerId
		}
		ajaxGet(url, params, function(data) {
			if (data.code === 200) {
				state.user.token = data.data.token;
				state.token = data.data.token;
				state.tokenTime = new Date().getTime() + '';
				app.setState(state);
				success(data.data.token);
			} else if (data.code === 3) {
				plus.nativeUI.closeToast();
				plus.nativeUI.closeWaiting();
				plus.nativeUI.toast("异地登录！");
				app.backLogin();
			} else {
				plus.nativeUI.toast(data.code+"  "+data.msg)
				// fail(data.msg);
				// plus.nativeUI.closeToast();
				// plus.nativeUI.closeWaiting();
				// app.backLogin();
			}
		}, function(errorMsg) {
			fail(errorMsg);
		});
	} else {
		success(token);
	}
}

function generateHeaders(url, params, success, fail) {
	var timeStamp = new Date().getTime() + '';
	var sign = generateSignature(params, timeStamp);
	console.log('timeStamp: ' + timeStamp);
	console.log('sign: ' + sign);

	var headers = null;
	if (url.indexOf("cc/login") !== -1) {
		headers = {
			'Content-Type': 'application/json',
			'sign': sign,
			'timeStamp': timeStamp, 
			'datetime': new Date().Format("yyyy-MM-dd HH:mm:ss")
		}
		success(headers);
	} else {
		// token
		getToken(function(token) {
			headers = {
				'Content-Type': 'application/json',
				'sign': sign,
				'token': token,
				'timeStamp': timeStamp,
				'datetime': new Date().Format("yyyy-MM-dd HH:mm:ss")
			}
			console.log("token: " + token);
			success(headers);
		}, function(errorMsg) {
			fail(errorMsg);
		});
	}
}

function errorHandl(xhr, type, errorThrown, fail) {
	var msg = "请求失败";
	// "timeout", "error", "abort", "parsererror"、"null"
	// 请求超时    请求异常   请求中止   解析异常 
	if (type === "timeout") {
		msg = "请求超时";
	} else if (type === "parsererror") {
		msg = "解析异常";
	}
	typeof fail === "function" ? fail(msg) : false;
}

/**
 * post请求
 * 
 * @param {String} url
 * @param {Json} params
 * @param {function} success
 * @param {function} fail
 */
function ajaxPost(url, params, success, fail) {
	var currentType = plus.networkinfo.getCurrentType()
	if (currentType === plus.networkinfo.CONNECTION_NONE || currentType === plus.networkinfo.CONNECTION_UNKNOW) {
		plus.nativeUI.closeWaiting()
		plus.nativeUI.closeToast()
		plus.nativeUI.toast("当前网络连接失败")
		return;
	}

	/*if(typeof(params) == "object"){
		var code = String.fromCharCode(8198)
		Object.keys(params).forEach(function (key) {
			params[key].split(code).join('!!!!!')
		})
		console.debug(params)
	}*/

	generateHeaders(url, params, function(headers) {
		// console.log("url:" + url);
		// console.log(JSON.stringify(headers))
		mui.ajax(encodeURI(url), {
			data: params,
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			timeout: timeout, //超时时间设置为10秒；
			headers: headers,
			success: function(data) {
				//服务器返回响应，根据响应结果，分析是否登录成功；
				// console.log(JSON.stringify(data));
				if (data.code === 3) {
					plus.nativeUI.closeToast();
					plus.nativeUI.closeWaiting();
					plus.nativeUI.toast("异地登录！");
					app.backLogin();
				} else {
					typeof success === "function" ? success(data) : false;
				}
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				// console.log(type);
				errorHandl(xhr, type, errorThrown, fail);
			}
		});
	}, function(errorMsg) {
		fail(errorMsg);
	});
}

/**
 * get请求
 * 
 * @param {String} url
 * @param {Json} params
 * @param {function} success
 * @param {function} fail
 */
function ajaxGet(url, params, success, fail) {
	var currentType = plus.networkinfo.getCurrentType()
	if (currentType === plus.networkinfo.CONNECTION_NONE || currentType === plus.networkinfo.CONNECTION_UNKNOW) {
		plus.nativeUI.closeWaiting()
		plus.nativeUI.closeToast()
		plus.nativeUI.toast("当前网络连接失败")
		return;
	}
	generateHeaders(url, params, function(headers) {
		// console.log(JSON.stringify(headers))
		var queryStr = Object.keys(params)
			.reduce((ary, key) => {
				if (params[key]) {
					ary.push(key + '=' + params[key]);
				}
				return ary;
			}, [])
			.join('&');
		url += `?${queryStr}`;
		console.log("url:" + url);
		mui.ajax(encodeURI(url), {
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: timeout, //超时时间设置为10秒；
			headers: headers,
			success: function(data) {
				//服务器返回响应，根据响应结果，分析是否登录成功；
				// console.log(JSON.stringify(data));
				if (data.code === 3) {
					plus.nativeUI.closeToast();
					plus.nativeUI.closeWaiting();
					plus.nativeUI.toast("异地登录！");
					app.backLogin();
				} else {
					typeof success === "function" ? success(data) : false;
				}
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				// console.log(type);
				errorHandl(xhr, type, errorThrown, fail);
			}
		});
	}, function(errorMsg) {
		fail(errorMsg);
	});
}

/**
 * 获取json数据
 * 
 * @param {Object} url
 * @param {Object} params
 * @param {Object} success
 */
function ajaxGetJson(url, params, success) {
	var currentType = plus.networkinfo.getCurrentType()
	if (currentType === plus.networkinfo.CONNECTION_NONE || currentType === plus.networkinfo.CONNECTION_UNKNOW) {
		plus.nativeUI.closeWaiting()
		plus.nativeUI.closeToast()
		plus.nativeUI.toast("当前网络连接失败")
		return;
	}
	ajaxGet(url, params, function(data) {
		if (data.code === 200) {
			typeof success === "function" ? success(data.data) : false;
		} else {
			app.closeWaiting()
			app.toast()
		}
	}, function(error) {
		app.closeWaiting()
		app.toast(error)
	})
}

/**
 * 文件上传
 * 
 * @param {Object} url 请求地址
 * @param {Object} path 本地文件路径
 * @param {Object} params 参数
 * @param {Object} success 成功回调
 * @param {Object} fail 失败回调
 * @param {Function} progress 上传进度回调
 */
function ajaxUploader(url, path, params, success, fail, progress) {
	var currentType = plus.networkinfo.getCurrentType()
	if (currentType === plus.networkinfo.CONNECTION_NONE || currentType === plus.networkinfo.CONNECTION_UNKNOW) {
		plus.nativeUI.closeWaiting()
		plus.nativeUI.closeToast()
		plus.nativeUI.toast("当前网络连接失败")
		return;
	}
	generateHeaders(url, params, function(headers) {
		var task = plus.uploader.createUpload(url, {
			method: 'POST'
		}, function(t, status) {
			if (status==200) {
				var data = JSON.parse(t.responseText);
				if (data.code === 3) {
					plus.nativeUI.closeToast();
					plus.nativeUI.closeWaiting();
					plus.nativeUI.toast("异地登录！");
					app.backLogin();
				} else {
					typeof success === "function" ? success(data) : false;
				}
			} else {
				fail("请求失败")
			}
		})
		
		if(headers) {
			for (var key in headers) {
				task.setRequestHeader(key, headers[key]);
			}
		}
		task.setRequestHeader('Content-Type', 'multipart/form-data');
		if (params) {
			for (var key in params) {
				task.addData(key, params[key] + '');
			}
		}
		task.addFile(path, {
			key: 'file'
		});
		task.addEventListener( "statechanged", function(upload, status) {
			if (200 !== status) {
				typeof progress === "function" ? progress(upload.totalSize, upload.uploadedSize) : false;
			}
		}, false );
		task.start();
	}, function(errorMsg) {
		fail(errorMsg);
	});
}

function ajaxGetNoneToken(url, params, success, fail) {
	var queryStr = Object.keys(params)
		.reduce((ary, key) => {
			if (params[key]) {
				ary.push(key + '=' + params[key]);
			}
			return ary;
		}, [])
		.join('&');
	url += `?${queryStr}`;
	console.log("url:" + url);
	mui.ajax(encodeURI(url), {
		dataType: 'json', //服务器返回json格式数据
		type: 'get', //HTTP请求类型
		timeout: timeout, //超时时间设置为10秒；
		success: function(data) {
			//服务器返回响应，根据响应结果，分析是否登录成功；
			// console.log(JSON.stringify(data));
			typeof success === "function" ? success(data) : false;
		},
		error: function(xhr, type, errorThrown) {
			//异常处理；
			// console.log(type);
			errorHandl(xhr, type, errorThrown, fail);
		}
	});
}
